<style lang="less">
  .insurance-record {
    .dialog-form-label {
      label {
        width: 120px;
      }

    }
    .dialog-form-content {
      width: 350px
    }
  }
</style>

<template>
  <div class="insurance-record">
    <search-bar moreDisplay>
      <el-row>
        <el-col :span="8">
          <el-form-item label="投保订单编号">
            <el-input v-model="condition['LIKE_orderNumber']" placeholder="请输入投保订单编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="投保日期">
            <el-col :span="11">
              <el-radio-group v-model="radio">
                <el-radio-button label="lastweek">上周</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="quarter">本季度</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="13">
              <el-date-picker
                v-model="daterange"
                type="daterange"
                placeholder="选择日期范围">
              </el-date-picker>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="投保状态">
            <el-select v-model="condition['EQ_orderInsuranceStatus']" placeholder="请选择投保状态">
              <el-option
                v-for="item in $store.getters.ORDER_INSURANCE_STATUS"
                :key="item.dictVal"
                :label="item.cnDictValname"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="投保方式">
            <el-select v-model="condition['EQ_orderInsurances.insuranceOperateType']" placeholder="请选择投保方式">
              <el-option
                v-for="item in $store.getters.SHIPMENT_TRACE_SOURCE"
                :key="item.dictVal"
                :label="item.cnDictValname"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="被保人名称">
            <el-input v-model="condition['LIKE_memberUserName']" placeholder="请输入被投保人名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="货物名称">
            <el-input v-model="condition['LIKE_orderCargos.cargoName']" placeholder="请输入货物名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <el-col :span="24" style="padding-bottom: 10px;border-bottom: 1px solid #d1dbe5;">
      <el-button type="primary" style="float: right" @click="reset">重置</el-button>
      <el-button type="primary" style="float: right;margin-right: 10px" @click="search">查询</el-button>
      <el-button type="primary" style="float: right">导出投保记录</el-button>
    </el-col>
    <el-table :data="tableData" v-loading="listLoading" highlight-current-row border style="width: 100%">
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="orderNumber" label="投保订单编号" width="120">
        <template slot-scope="scope">
          <el-button type="text" style="padding: 0;" @click="openDialog(scope.row.orderId,scope.row.orderNumber)">
            {{scope.row.orderNumber}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="orderCreateDate" label="下单日期" width="150">
      </el-table-column>
      <el-table-column prop="createDate" width="150" label="投保日期">
      </el-table-column>
      <el-table-column prop="insuranceStatusName" width="100" label="投保状态">
      </el-table-column>
      <el-table-column prop="insuranceOperateTypeName" width="100" label="投保方式">
      </el-table-column>
      <el-table-column prop="goodsValue" width="120" label="保价金额(万元)">
        <template slot-scope="scope">
          {{(scope.row.goodsValue / 10000).toFixed(2)}}
        </template>
      </el-table-column>
      <el-table-column prop="insuranceFee" width="120" label="投保订单保费(元)">
      </el-table-column>
      <el-table-column prop="total" width="120" label="保费成本(元)">
      </el-table-column>
      <el-table-column prop="shipmentsContactName" width="120" label="被保人名称">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="shipmentsRegion" width="180" label="起始地">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="sendRegion" width="180" label="目的地">
      </el-table-column>
      <el-table-column prop="cargoNames" width="120" label="货物名称">
      </el-table-column>
      <el-table-column prop="packTypeNames" width="100" label="包装类型">
      </el-table-column>
      <el-table-column prop="amount" width="100" label="件数">
      </el-table-column>
      <el-table-column prop="orderStatusName" width="100" label="订单状态">
      </el-table-column>
      <el-table-column prop="couponPrice" width="120" label="优惠抵扣(元)">
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="160" align="center">
        <template slot-scope="scope">
          <el-button type="primary"
                     v-if="scope.row.insuranceStatus === 101028001 || scope.row.insuranceStatus === 101028003"
                     @click="applyForInsuranceOnLine(scope.$index,scope.row)" style="width: 120px;margin-left: 0px">
            申请线上投保
          </el-button>
          <el-button type="primary"
                     v-if="scope.row.insuranceStatus === 101028001 || scope.row.insuranceStatus === 101028003"
                     @click="applyForInsuranceOffLine(scope.$index,scope.row)"
                     style="width: 120px;margin-left: 0px;margin-top: 5px">已线下投保
          </el-button>
          <el-button type="danger" v-if="scope.row.insuranceStatus === 101028002"
                     @click="backoutInsurance(scope.$index,scope.row)"
                     style="width: 120px;margin-left: 0px;margin-top: 5px">撤销投保
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="page"
        :page-size="size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <order-track-detail ref="orderTrackDetail"></order-track-detail>
    <el-dialog :title="dialogTitle" @close="resetDialogForm" :visible.sync="dialogFormVisible" size="tiny">
      <el-form :key="dialogKey" :model="dialogForm" ref="dialogForm" :rules="rules">
        <el-form-item label="订单id" class="dialog-form-label" style="display: none">
          <el-input v-model="dialogForm.orderId" style="width: 220px" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单号" class="dialog-form-label">
          <el-input v-model="dialogForm.orderNumber" class="dialog-form-content" disabled="disabled"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="保单号" prop="policyNo" class="dialog-form-label">
          <el-input v-model="dialogForm.policyNo" class="dialog-form-content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="投保状态" class="dialog-form-label">
          <el-select v-model="dialogForm.insuranceStatus" placeholder="请选择投保状态" disabled="disabled"
                     class="dialog-form-content">
            <el-option
              v-for="item in $store.getters.ORDER_INSURANCE_STATUS"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保险公司类型" prop="insuranceCompanyType" class="dialog-form-label">
          <el-select v-model="dialogForm.insuranceCompanyType" disabled="disabled" class="dialog-form-content">
            <el-option
              v-for="item in $store.getters.ORDER_INSURANCE_COMPANY_TYPE"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投保日期" class="dialog-form-label" prop="createDate">
          <el-date-picker
            format="yyyy-MM-dd HH:mm"
            v-model="dialogForm.createDate"
            type="datetime"
            style="width: 350px"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保单生效日期" class="dialog-form-label" prop="policyEffect">
          <el-date-picker
            format="yyyy-MM-dd HH:mm"
            v-model="dialogForm.policyEffect"
            type="datetime"
            style="width: 350px"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保单失效日期" class="dialog-form-label" prop="policyExpire">
          <el-date-picker
            format="yyyy-MM-dd HH:mm"
            v-model="dialogForm.policyExpire"
            type="datetime"
            style="width: 350px"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保单金额" prop="total" class="dialog-form-label">
          <el-input type="number" v-model="dialogForm.total" class="dialog-form-content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单保费" prop="insuranceFee" class="dialog-form-label">
          <el-input v-model="dialogForm.insuranceFee" class="dialog-form-content" disabled="disabled"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="保价金额" prop="goodsValue" class="dialog-form-label">
          <el-input type="number" v-model="dialogForm.goodsValue" class="dialog-form-content"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="投保方式" class="dialog-form-label">
          <el-select v-model="dialogForm.insuranceOperateType" placeholder="请选择投保方式" disabled="disabled"
                     class="dialog-form-content">
            <el-option
              v-for="item in $store.getters.SHIPMENT_TRACE_SOURCE"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm()">取 消</el-button>
        <el-button type="primary" @click.native="offLineSubmit()" :loading="submitLoading">提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderInsuranceRecords, insuranceOnLine, saveInsuranceOffLine } from '../../api/order/OrderInsurance';
import OrderTrackDetail from './OrderTrackDetail.vue';

export default {
  name: 'OrderInsuranceRecord',
  components: {OrderTrackDetail},
  data: function () {
    return {
      condition: {
        'LIKE_orderNumber': null,
        'LIKE_memberUserName': null,
        'LIKE_orderCargos.cargoName': null,
        'EQ_orderInsurances.insuranceOperateType': null,
        'EQ_orderInsuranceStatus': null
      },
      radio: 'lastweek',
      daterange: [],
      page: 1,
      size: 10,
      total: 0,
      listLoading: false,
      tableData: [],
      // 线下投保确认弹框
      dialogTitle: '线下投保明细',
      dialogFormVisible: false,
      dialogKey: null,
      dialogForm: {
        'orderId': null,
        'orderNumber': null,
        'policyNo': null,
        'insuranceStatus': null,
        'insuranceCompanyType': null,
        'createDate': null,
        'policyEffect': null,
        'policyExpire': null,
        'total': null,
        'insuranceFee': null,
        'goodsValue': null,
        'insuranceOperateType': null
      },
      submitLoading: false,
      rules: {
        policyNo: [
          {required: true, message: '请输入保单号', trigger: 'blur'}
        ],
        createDate: [
          {type: 'date', required: true, message: '请选择投保日期', trigger: 'blur'}
        ],
        total: [
          {required: true, message: '请输入保单金额', trigger: 'blur'}
        ],
        goodsValue: [
          {required: true, message: '请输入保价金额', trigger: 'blur'}
        ]
      }
    };
  },
  watch: {
    radio (val) {
      if (val === 'lastweek') {
        this.lastWeek();
      } else if (val === 'week') {
        this.week();
      } else if (val === 'month') {
        this.month();
      } else {
        this.quarter();
      }
    }
  },
  methods: {
    handleSubmit () {},
    openDialog (orderId, orderNumber) {
      this.$refs.orderTrackDetail.show(orderId, orderNumber);
    },
    search () {
      let filters = this.$ue.objToFilter(this.condition);
      filters += ';GT_confirmTime=' + this.daterange[0].toJSON();
      filters += ';LT_confirmTime=' + this.$ue.addDays(this.daterange[1], 1).toJSON();
      this.loadAllOrderInsurances(filters);
    },
    reset () {
      this.$ue.resetObjNull(this.condition);
    },
    handleSizeChange (size) {
      this.size = size;
      this.search();
    },
    handleCurrentPageChange (page) {
      this.page = page;
      this.search();
    },
    loadAllOrderInsurances (filters = '') {
      getOrderInsuranceRecords({
        filters: filters,
        page: this.page,
        size: this.size
      }).then(res => {
        if (res.data.successFlg) {
          this.tableData = res.data.detailModelList;
          this.total = res.data.totalCount;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    lastWeek () {
      this.daterange = this.$ue.getLastWeek();
    },
    week () {
      this.daterange = this.$ue.getThisWeek();
    },
    month () {
      this.daterange = this.$ue.getThisMonthNew();
    },
    quarter () {
      this.daterange = this.$ue.getThisQuarterNew();
    },

    // 申请线上投保
    applyForInsuranceOnLine (index, row) {
      this.$confirm('由于接口问题或其他原因导致自动投保失败，您需要再次申请线上投保么?', '提示', {
        type: 'info'
      }).then(() => {
        insuranceOnLine(row.orderId).then(res => {
          if (res.data.successFlg) {
            this.$message.success('投保申请操作成功！');
            this.search();
          } else {
            this.$message.error('投保申请操作失败!');
          }
        });
      }).catch(() => {
        this.$message.error('数据有误，请求失败！');
      });
    },
    // 线下投保确认
    applyForInsuranceOffLine (index, row) {
      this.dialogForm.orderId = row.orderId;
      this.dialogForm.orderNumber = row.orderNumber;
      this.dialogForm.insuranceStatus = 101028002;
      this.dialogForm.insuranceCompanyType = row.insuranceCompanyType;
      this.dialogForm.insuranceFee = row.insuranceFee;
      this.dialogForm.insuranceOperateType = 105009002;
      this.dialogKey = Math.random() - 0.5;
      this.dialogFormVisible = true;
    },
    resetDialogForm () {
      for (let p in this.dialogForm) {
        if (this.dialogForm[p] instanceof Array) {
          this.dialogForm[p] = [];
        } else {
          this.dialogForm[p] = null;
        }
      }
      this.dialogFormVisible = false;
    },
    // submit
    offLineSubmit () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.dialogForm.userId = this.userId;
          saveInsuranceOffLine(this.dialogForm).then((res) => {
            this.submitLoading = false;
            if (res.data.successFlg === true) {
              this.dialogFormVisible = false;
              this.$message.success('操作成功！');
              this.search();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            this.$message.error('数据有误，操作失败！');
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 撤销投保
    backoutInsurance (index, row) {
      this.$confirm('此订单已经成功投保，需要申请系统撤销投保么?', '提示', {
        type: 'info'
      }).then(() => {
        this.$message.error('抱歉，已经投保成功的订单，暂不允许撤保！');
      }).catch(() => {
        this.$message.error('数据有误，请求失败！');
      });
    }
  },
  mounted () {
    this.$store.commit('initDict');
    this.lastWeek();
    this.search();
  }
};
</script>
